<template>
  <div class="order-form-page">
    <div class="page-header-fixed">
      <div class="header-left">
        <a class="back-link" @click="handleBack">
          <ArrowLeftOutlined />
          <span>返回收货开票</span>
        </a>
        <div class="header-title-area">
          <h2>{{ isEdit ? "编辑收货开票" : "新增收货开票" }}</h2>
          <a-tag
            v-if="isEdit && orderData"
            :color="ORDER_STATUS_CONFIG[orderData.orderStatus]?.color"
          >
            {{
              ORDER_STATUS_CONFIG[orderData.orderStatus]?.label ||
              orderData.orderStatus
            }}
          </a-tag>
        </div>
        <p class="header-desc">
          {{
            isEdit
              ? `运单号：${
                  orderData?.orderNo || "-"
                } · 查看并更新收货、货物与费用信息`
              : "填写收货、货物及费用信息，保存后系统自动生成运单号"
          }}
        </p>
      </div>
      <div class="header-actions">
        <a-space>
          <a-button @click="handleBack">取消</a-button>
          <a-button
            type="primary"
            :loading="submitting"
            :disabled="isEdit && !orderData"
            @click="handleSubmit"
          >
            {{ isEdit ? "保存修改" : "保存开票" }}
          </a-button>
        </a-space>
      </div>
    </div>

    <div class="page-content">
      <a-spin :spinning="loading" tip="加载中...">
        <a-card class="form-card">
          <a-alert
            v-if="isEdit && isTransporting"
            message="运输中的订单仅支持修改收货信息和备注"
            type="warning"
            show-icon
            style="margin-bottom: 16px"
          />
          <a-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            layout="vertical"
          >
            <div class="form-section">
              <div class="section-header">
                <span class="section-title">基础信息</span>
              </div>
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="运单号">
                    <a-input
                      :value="
                        isEdit ? orderData?.orderNo : '保存后系统自动生成'
                      "
                      disabled
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="数字编码" name="goodsCode">
                    <a-input
                      v-model:value="formData.goodsCode"
                      placeholder="请输入数字编码，例如 15-6"
                      :disabled="isTransporting"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="开票员">
                    <a-input :value="issuerName" disabled />
                  </a-form-item>
                </a-col>
              </a-row>
            </div>

            <div class="form-section">
              <div class="section-header">
                <span class="section-title">站点与联系人</span>
              </div>
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="发货站点" name="departureSiteId">
                    <a-select
                      v-model:value="formData.departureSiteId"
                      placeholder="请选择发货站点"
                      :loading="siteLoading"
                      :disabled="isTransporting || shouldLockDepartureSite"
                      allowClear
                    >
                      <a-select-option
                        v-for="site in siteOptions"
                        :key="site.id"
                        :value="site.id"
                        :disabled="site.id === formData.arrivalSiteId"
                      >
                        {{ site.siteName }}
                        <span
                          v-if="site.id === formData.arrivalSiteId"
                          style="color: #999"
                        >
                          （不能选择到货站点）
                        </span>
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="到货站点" name="arrivalSiteId">
                    <a-select
                      v-model:value="formData.arrivalSiteId"
                      placeholder="请选择到货站点"
                      :loading="siteLoading"
                      :disabled="isTransporting"
                      allowClear
                    >
                      <a-select-option
                        v-for="site in siteOptions"
                        :key="`arrival-${site.id}`"
                        :value="site.id"
                        :disabled="site.id === formData.departureSiteId"
                      >
                        {{ site.siteName }}
                        <span
                          v-if="site.id === formData.departureSiteId"
                          style="color: #999"
                        >
                          （不能选择发货站点）
                        </span>
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="发货人" name="senderName">
                    <a-input
                      v-model:value="formData.senderName"
                      placeholder="请输入发货人"
                      :disabled="isTransporting"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="发货电话" name="senderPhone">
                    <a-input
                      v-model:value="formData.senderPhone"
                      placeholder="请输入发货电话"
                      :disabled="isTransporting"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="收货人" name="receiverName">
                    <a-input
                      v-model:value="formData.receiverName"
                      placeholder="请输入收货人"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="收货电话" name="receiverPhone">
                    <a-input
                      v-model:value="formData.receiverPhone"
                      placeholder="请输入收货电话"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="配送方式" name="deliveryType">
                    <a-radio-group v-model:value="formData.deliveryType">
                      <a-radio value="DELIVERY">送货上门</a-radio>
                      <a-radio value="PICKUP">到站自提</a-radio>
                    </a-radio-group>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="附加选项" name="deliveryOptions">
                    <a-checkbox-group v-model:value="formData.deliveryOptions">
                      <a-checkbox value="SIGN_RECEIPT">签回单</a-checkbox>
                      <a-checkbox value="PRINT_RECEIPT">打收条</a-checkbox>
                    </a-checkbox-group>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16" v-if="formData.deliveryType === 'DELIVERY'">
                <a-col :span="24">
                  <a-form-item label="收货地址" name="receiverAddress">
                    <a-input
                      v-model:value="formData.receiverAddress"
                      placeholder="请输入收货地址"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </div>

            <div class="form-section">
              <div class="section-header">
                <span class="section-title">货物信息</span>
              </div>
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="货物名称" name="goodsName">
                    <a-input
                      v-model:value="formData.goodsName"
                      placeholder="请输入货物名称"
                      :disabled="isTransporting"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="包装方式">
                    <a-input
                      v-model:value="formData.goodsPackage"
                      placeholder="请输入包装方式"
                      :disabled="isTransporting"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="件数" name="goodsPieces">
                    <a-input-number
                      v-model:value="formData.goodsPieces"
                      :min="1"
                      :precision="0"
                      style="width: 100%"
                      :disabled="isTransporting"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="备注">
                    <a-textarea
                      v-model:value="formData.remark"
                      placeholder="填写额外说明（可选）"
                      :rows="2"
                      :maxlength="200"
                      show-count
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </div>

            <div class="form-section">
              <div class="section-header">
                <span class="section-title">运输资源</span>
              </div>
              <a-row :gutter="16">
                <a-col :span="24">
                  <a-form-item label="司机">
                    <a-select
                      v-model:value="formData.driverId"
                      placeholder="请选择司机（可选）"
                      :loading="driverLoading"
                      :disabled="isTransporting"
                      allowClear
                    >
                      <a-select-option
                        v-for="driver in driverList"
                        :key="driver.id"
                        :value="driver.id"
                      >
                        {{ driver.name }}（{{ driver.phone }}）
                      </a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
            </div>

            <div class="form-section">
              <div class="section-header">
                <span class="section-title">费用信息</span>
              </div>
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="实收运费" name="freightAmount">
                    <a-input-number
                      v-model:value="formData.freightAmount"
                      :min="0"
                      :precision="2"
                      placeholder="客户支付的运费"
                      style="width: 100%"
                      :disabled="isTransporting"
                    >
                      <template #addonAfter>元</template>
                    </a-input-number>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="结算运费" name="settlementAmount">
                    <a-input-number
                      v-model:value="formData.settlementAmount"
                      :min="0"
                      :precision="2"
                      placeholder="给到货站点的结算金额"
                      style="width: 100%"
                      :disabled="isTransporting"
                    >
                      <template #addonAfter>元</template>
                    </a-input-number>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item label="代收款">
                    <a-input-number
                      v-model:value="formData.collectionAmount"
                      :min="0"
                      :precision="2"
                      placeholder="请输入代收款（可选）"
                      style="width: 100%"
                      :disabled="isTransporting"
                    >
                      <template #addonAfter>元</template>
                    </a-input-number>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="付款方式" name="paymentMethod">
                    <a-select
                      v-model:value="formData.paymentMethod"
                      placeholder="请选择付款方式"
                      :options="paymentMethodOptions"
                      :disabled="isTransporting"
                    />
                  </a-form-item>
                </a-col>
              </a-row>
            </div>
            <div class="form-section">
              <a-space>
                <a-button
                  type="primary"
                  :loading="submitting"
                  :disabled="isEdit && !orderData"
                  @click="handleSubmit"
                >
                  {{ isEdit ? "保存修改" : "保存开票" }}
                </a-button>
                <a-button @click="handleBack">取消</a-button>
              </a-space>
            </div>
          </a-form>
        </a-card>
      </a-spin>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { message } from "ant-design-vue";
import type { FormInstance } from "ant-design-vue";
import { ArrowLeftOutlined } from "@ant-design/icons-vue";
import { createOrder, getOrderById, updateOrder } from "@/api/tenant/order";
import { getSiteList } from "@/api/tenant/site";
import { getDriverList } from "@/api/tenant/driver";
import { useDictionary } from "@/composables/useDictionary";
import { useUserStore } from "@/stores/user";
import type {
  Order,
  OrderCreateParams,
  OrderUpdateParams,
} from "@/types/order";
import { ORDER_STATUS_CONFIG } from "@/types/order";
import type { Site } from "@/types/site";
import type { Driver } from "@/types/driver";

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

const formRef = ref<FormInstance>();
const loading = ref(false);
const submitting = ref(false);
const orderData = ref<Order | null>(null);

const siteOptions = ref<Site[]>([]);
const siteLoading = ref(false);
const driverList = ref<Driver[]>([]);
const driverLoading = ref(false);

// 不使用缓存，每次都从数据库实时获取最新的支付方式选项
// 这样删除字典后，新增订单时立即生效
const { options: paymentMethodOptions, loadDictionaries: loadPaymentMethods } =
  useDictionary("PAYMENT_METHOD", false);

const isEdit = computed(() => route.name === "OrderEdit");
const isTransporting = computed(
  () => isEdit.value && orderData.value?.orderStatus === "TRANSPORTING"
);

const issuerName = computed(() => {
  if (isEdit.value && orderData.value) {
    return orderData.value.issuerName || "-";
  }
  return userStore.userInfo?.realName || userStore.userInfo?.username || "-";
});

// 计算是否需要锁定发货站点
// 只有超级管理员在"全部站点"模式下才能自由选择发货站点
const shouldLockDepartureSite = computed(() => {
  const isSuperAdmin = userStore.userInfo?.role === "SUPER_ADMIN";
  const isViewingAllSites = userStore.userInfo?.siteId === null;
  return !isSuperAdmin || !isViewingAllSites;
});

const formData = reactive<
  OrderCreateParams & {
    departureSiteName?: string;
    arrivalSiteName?: string;
    goodsPackage?: string;
    collectionAmount?: number;
    siteId?: number;
    goodsCode?: string;
    goodsPieces: number;
    remark?: string;
    deliveryOptions: string[];
  }
>({
  siteId: userStore.userInfo?.siteId,
  goodsCode: "",
  departureSiteId: undefined,
  departureSiteName: undefined,
  arrivalSiteId: undefined,
  arrivalSiteName: undefined,
  senderName: "",
  senderPhone: "",
  receiverName: "",
  receiverPhone: "",
  deliveryType: "DELIVERY",
  deliveryOptions: [],
  receiverAddress: "",
  goodsName: "",
  goodsPackage: "",
  goodsPieces: 1,
  freightAmount: 0,
  settlementAmount: 0, // 结算运费
  collectionAmount: 0,
  paymentMethod: "",
  driverId: undefined,
  remark: "",
});

const rules = {
  goodsCode: [{ required: true, message: "请输入数字编码" }],
  departureSiteId: [{ required: true, message: "请选择发货站点" }],
  arrivalSiteId: [{ required: true, message: "请选择到货站点" }],
  senderName: [{ required: true, message: "请输入发货人" }],
  senderPhone: [
    { required: true, message: "请输入发货电话" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码" },
  ],
  receiverName: [{ required: true, message: "请输入收货人" }],
  receiverPhone: [
    { required: true, message: "请输入收货电话" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码" },
  ],
  deliveryType: [{ required: true, message: "请选择配送方式" }],
  goodsName: [{ required: true, message: "请输入货物名称" }],
  goodsPieces: [{ required: true, type: "number", message: "请输入件数" }],
  freightAmount: [{ required: true, message: "请输入实收运费" }],
  settlementAmount: [{ required: true, message: "请输入结算运费" }],
  paymentMethod: [{ required: true, message: "请选择付款方式" }],
};

const loadSites = async () => {
  siteLoading.value = true;
  try {
    const siteResponse = await getSiteList();
    siteOptions.value = (siteResponse.data ?? []) as unknown as Site[];
  } catch (error) {
    console.error("获取站点列表失败:", error);
  } finally {
    siteLoading.value = false;
  }
};

const loadDrivers = async () => {
  driverLoading.value = true;
  try {
    const userStore = useUserStore();
    const currentSiteId = userStore.userInfo?.siteId;

    const driverResponse = await getDriverList({
      current: 1,
      size: 100,
      driverStatus: isEdit.value ? undefined : "IDLE",
      siteId: currentSiteId, // 只获取当前站点的司机
    });
    const data = driverResponse.data as any;
    driverList.value = data?.records ?? [];
  } catch (error) {
    console.error("获取司机列表失败:", error);
  } finally {
    driverLoading.value = false;
  }
};

// 注意：车辆和司机已解除绑定关系，不再自动联动
// 车辆分配将在后续运单装车功能中进行

const fetchOrderDetail = async () => {
  const id = Number(route.params.id);
  if (!id) {
    message.error("订单ID无效");
    handleBack();
    return;
  }
  loading.value = true;
  try {
    const orderResponse = await getOrderById(id);
    const order = orderResponse.data as any;
    orderData.value = order;
    Object.assign(formData, {
      goodsCode: order.goodsCode,
      departureSiteId: order.departureSiteId || undefined,
      arrivalSiteId: order.arrivalSiteId || undefined,
      senderName: order.senderName,
      senderPhone: order.senderPhone,
      receiverName: order.receiverName,
      receiverPhone: order.receiverPhone,
      deliveryType: order.deliveryType || "DELIVERY",
      deliveryOptions: order.deliveryOptions
        ? order.deliveryOptions.split(",")
        : [],
      receiverAddress: order.receiverAddress || "",
      goodsName: order.goodsName,
      goodsPackage: order.goodsPackage || "",
      goodsPieces: order.goodsPieces || 1,
      freightAmount: order.freightAmount || 0,
      settlementAmount: order.settlementAmount || 0,
      collectionAmount: order.collectionAmount || 0,
      paymentMethod: order.paymentMethod,
      vehicleId: order.vehicleId || undefined,
      driverId: order.driverId || undefined,
      remark: order.remark || "",
    });
  } catch (error) {
    console.error("获取订单详情失败:", error);
    message.error("获取订单详情失败");
    handleBack();
  } finally {
    loading.value = false;
  }
};

const handleSubmit = async () => {
  try {
    await formRef.value?.validate();
    submitting.value = true;

    const departureSite = siteOptions.value.find(
      (site) => site.id === formData.departureSiteId
    );
    const arrivalSite = siteOptions.value.find(
      (site) => site.id === formData.arrivalSiteId
    );

    const payload = {
      goodsCode: formData.goodsCode?.trim(),
      departureSiteId: formData.departureSiteId!,
      departureSiteName: departureSite?.siteName,
      arrivalSiteId: formData.arrivalSiteId!,
      arrivalSiteName: arrivalSite?.siteName,
      senderName: formData.senderName.trim(),
      senderPhone: formData.senderPhone.trim(),
      receiverName: formData.receiverName.trim(),
      receiverPhone: formData.receiverPhone.trim(),
      deliveryType: formData.deliveryType,
      deliveryOptions:
        formData.deliveryOptions?.length > 0
          ? formData.deliveryOptions.join(",")
          : undefined,
      receiverAddress: formData.receiverAddress?.trim() || undefined,
      goodsName: formData.goodsName.trim(),
      goodsPackage: formData.goodsPackage?.trim() || undefined,
      goodsPieces: Number(formData.goodsPieces || 0),
      freightAmount: Number(formData.freightAmount || 0),
      settlementAmount: Number(formData.settlementAmount || 0),
      collectionAmount:
        formData.collectionAmount !== undefined
          ? Number(formData.collectionAmount)
          : 0,
      paymentMethod: formData.paymentMethod!,
      driverId: formData.driverId || undefined,
      remark: formData.remark?.trim() || "",
    };

    if (isEdit.value && orderData.value) {
      await updateOrder(orderData.value.id, payload as OrderUpdateParams);
      message.success("收货开票更新成功");
    } else {
      await createOrder({
        ...payload,
        siteId: formData.siteId,
      } as OrderCreateParams);
      message.success("收货开票创建成功");
    }

    router.push("/tenant/order");
  } catch (error: any) {
    if (error?.errorFields) {
      // 表单校验错误
      return;
    }
    console.error(`${isEdit.value ? "更新" : "创建"}收货开票失败:`, error);
    if (error?.message && error.message !== "Error") {
      message.error(error.message);
    }
  } finally {
    submitting.value = false;
  }
};

const handleBack = () => {
  router.push("/tenant/order");
};

onMounted(async () => {
  await Promise.all([loadPaymentMethods(), loadSites(), loadDrivers()]);

  if (isEdit.value) {
    await fetchOrderDetail();
  } else {
    // 新增订单时，如果不是超级管理员或超级管理员选择了具体站点，默认设置发货站点为当前站点
    if (shouldLockDepartureSite.value && userStore.userInfo?.siteId) {
      formData.departureSiteId = userStore.userInfo.siteId;
    }
  }

  if (!formData.paymentMethod && paymentMethodOptions.value.length > 0) {
    formData.paymentMethod = paymentMethodOptions.value[0].value as string;
  }
});
</script>

<style scoped>
.order-form-page {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.page-header-fixed {
  flex-shrink: 0;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  background: #fff;
  padding-bottom: 16px;
  margin-bottom: 16px;
  border-bottom: 1px solid var(--border-color);
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.header-title-area {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-title-area h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
}

.header-desc {
  margin: 0;
  font-size: 13px;
  color: var(--text-secondary);
}

.back-link {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  color: var(--text-secondary);
  cursor: pointer;
  transition: color var(--transition-fast);
}

.back-link:hover {
  color: var(--primary-color);
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-content {
  flex: 1;
  overflow: auto;
  padding: 0 16px 16px;
}

.form-card {
  max-width: 960px;
  border: none;
  box-shadow: var(--shadow-card);
}

::deep(.form-card .ant-card-body) {
  padding: 28px;
}

.form-section {
  margin-bottom: 32px;
}

.form-section:last-of-type {
  margin-bottom: 0;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.section-title {
  position: relative;
  padding-left: 12px;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

.section-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 2px;
  bottom: 2px;
  width: 4px;
  border-radius: 4px;
  background: var(--primary-color);
}

.section-subtitle {
  font-size: 13px;
  color: var(--text-secondary);
}

::deep(.ant-form-item) {
  margin-bottom: 20px;
}

::deep(.ant-form-item-label > label) {
  font-weight: 500;
  color: var(--text-primary);
}

::deep(.ant-input[disabled]) {
  color: var(--text-secondary);
}

::deep(.ant-select),
::deep(.ant-input-number) {
  width: 100%;
}

@media (max-width: 992px) {
  .page-header-fixed {
    flex-direction: column;
    gap: 12px;
  }

  .header-actions {
    align-self: flex-end;
  }
}
</style>
